import 'package:get/get.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebviewController extends GetxController {
  // 响应式变量
  final isLoading = true.obs;
  final hasError = false.obs;

  // WebView控制器
  late WebViewController webViewController;

  // 页面参数
  String get url => Get.arguments?['url'] ?? '';
  String get title => Get.arguments?['title'] ?? '网页';

  @override
  void onInit() {
    super.onInit();
    print('打开网页: $title - $url');
    _initWebView();
  }

  /// 初始化WebView
  void _initWebView() {
    webViewController =
        WebViewController()
          ..setJavaScriptMode(JavaScriptMode.unrestricted)
          ..setNavigationDelegate(
            NavigationDelegate(
              onPageStarted: (String url) {
                isLoading.value = true;
                hasError.value = false;
              },
              onPageFinished: (String url) {
                isLoading.value = false;
              },
              onWebResourceError: (WebResourceError error) {
                isLoading.value = false;
                hasError.value = true;
                print('WebView加载错误: ${error.description}');
              },
              onNavigationRequest: (NavigationRequest request) {
                // 允许所有导航请求
                return NavigationDecision.navigate;
              },
            ),
          );

    // 加载URL
    _loadUrl();
  }

  /// 加载URL
  void _loadUrl() {
    String targetUrl = url;

    // 如果URL不包含协议，添加https://
    if (!targetUrl.startsWith('http://') && !targetUrl.startsWith('https://')) {
      targetUrl = 'https://$targetUrl';
    }

    try {
      webViewController.loadRequest(Uri.parse(targetUrl));
    } catch (e) {
      hasError.value = true;
      isLoading.value = false;
      print('加载URL失败: $e');
    }
  }

  /// 重试加载
  void retry() {
    hasError.value = false;
    isLoading.value = true;
    _loadUrl();
  }

  /// 关闭页面
  void close() {
    Get.back();
  }
}
